<template>
    <div>
    <van-card
        v-for="team in props.teamList"
        :desc="team.description"
        :title="team.name"
        :thumb="kunKunBasketball"
    >
      <template #tags>
        <van-tag mark type="primary"
                 v-if="team.status === 0"
                 size="medium"
                 color="#1889f9"
                 style="margin-right: 8px;"
                 id="publicTag">
          {{// @ts-ignore
            teamStatusEnum[team.status]
          }}
        </van-tag>
        <van-tag mark type="primary"
                 v-if="team.status === 2"
                 size="medium"
                 color="#7232dd"
                 style="margin-right: 8px;"
                 id="secretTag">
          {{// @ts-ignore
        teamStatusEnum[team.status]
          }}
        </van-tag>
        <van-tag mark type="primary"
                 v-if="team.status === 1"
                 size="medium"
                 color="#EE0A25"
                 style="margin-right: 8px;"
                 id="privateTag">
          {{// @ts-ignore
        teamStatusEnum[team.status]
          }}
        </van-tag>
      </template>
      <template #bottom>
        <div class="showTeamInfo">
          <div>
            {{
              `队伍人数：${team.hasJoinNum}/${team.maxNum}`
            }}
          </div>
          <div>
            {{
              `过期时间：${moment(team.expireTime).format("YYYY-MM-DD")}`
            }}
          </div>
          <div>
            {{
              `创建时间：${moment(team.createTime).format("YYYY-MM-DD")}`
            }}
          </div>
        </div>
      </template>
      <template #footer>
        <van-button v-if="!team.hasJoin && team.userId !== currentUser?.id" round type="success" size="small"
                    @click="preJoinTeam(team)" class="operateTeamButton">加入队伍
        </van-button>
        <van-button v-if="team.userId === currentUser?.id || currentUser?.userRole === 1" round type="primary" size="small"
                    @click="toUpdateTeamPage(team.id)" class="operateTeamButton">更新队伍
        </van-button>
        <van-button v-if="team.hasJoin" round type="primary" size="small"
                    @click="doQuitTeam(team.id)" class="operateTeamButton">退出队伍
        </van-button>
        <van-button v-if="team.userId === currentUser?.id || currentUser?.userRole === 1" round type="danger" size="small"
                    @click="preDisbandTeam(team.id)" id="disbandTeamButton" class="operateTeamButton">解散队伍
        </van-button>
      </template>
    </van-card>
   </div>
    <van-dialog v-model:show="showPasswordDialog" title="请输入队伍密码" show-cancel-button @confirm="doJoinTeam" @cancel="emptyJoinTeamData">
      <van-field v-model="password" type="password" label="密码" placeholder="请输入队伍密码"/>
    </van-dialog>
  <van-dialog v-model:show="showDisbandTeamDialog"
              confirmButtonColor="#EE0A24"
              show-cancel-button
              @confirm="doDisbandTeam(disbandTeamId)">
    <van-divider>
      <van-highlight :keywords="keywordsDisband" :source-string="textDisband" id="keywordsDisbandTeamFontSize"/>
    </van-divider>
  </van-dialog>
</template>

<script setup lang="ts">

import { TeamType } from "../models/team";
import {teamStatusEnum} from "../constants/team";
import kunKunBasketball from "../assets/kunkunBasketball.png";
import myAxios from "../plugins/myAxios.ts";
import {showFailToast, showSuccessToast} from "vant";
import {getCurrentUser} from "../services/user.ts";
import {onMounted, ref} from "vue";
import {useRouter} from "vue-router";
import moment from "moment/moment";

interface TeamCardListProps {
  teamList: TeamType[];
}

const router = useRouter();
const showPasswordDialog = ref(false);
const showDisbandTeamDialog = ref(false);
const password = ref('');

const textDisband = '请确定解散队伍'
const keywordsDisband = '请确定解散队伍'

const props = withDefaults(defineProps<TeamCardListProps>(), {
  // @ts-ignore
  teamList: [] as TeamType[],
})
const joinTeamId = ref();
const currentUser = ref();
const disbandTeamId = ref();

// 获取当前用户
onMounted(async () => {
  currentUser.value = await getCurrentUser();
})

/**
 * 预加入队伍（判断是否为加密队伍）
 * @param team
 */
const preJoinTeam = (team: TeamType) => {
  joinTeamId.value = team.id;
  if(team.status === 0) {
    doJoinTeam();
  } else {
    showPasswordDialog.value = true;
  }
}

/**
 * 预解散队伍
 * @param teamId
 */
const preDisbandTeam = (teamId: number) => {
  disbandTeamId.value = teamId;
  showDisbandTeamDialog.value = true;
}

/**
 * 清空加入队伍数据
 */
const emptyJoinTeamData = () => {
  password.value = '';
  joinTeamId.value = 0;
}

/**
 * 加入队伍
 */
// @ts-ignore
const doJoinTeam = async () => {
  if(!joinTeamId) {
    return;
  }
  const res = await myAxios.post('/team/join', {
    teamId: joinTeamId.value,
    password: password.value,
  });
  // @ts-ignore
  if(res?.code === 0) {
    showSuccessToast('加入队伍成功');
    // location.reload();
    // 本地响应更新
    const teamIndex = props.teamList.findIndex(t => t.id === joinTeamId.value);
    if (teamIndex!== -1) {
      props.teamList[teamIndex].hasJoin = true;
      // @ts-ignore
      props.teamList[teamIndex].hasJoinNum = props.teamList[teamIndex].hasJoinNum + 1;
    }
  } else {
    // @ts-ignore
    showFailToast('加入队伍失败' + (res.description ? `${res.description}` : ''));
  }
  //加入队伍成功与否 均要清空弹窗内的加入队伍密码数据
  emptyJoinTeamData();
}

/**
 * 跳转更新队伍页
 * @param id
 */
const toUpdateTeamPage = (id: number) => {
  router.push({
    path: '/team/update',
    query: {
      id,
    }
  })
}

/**
 * 退出队伍
 * @param id
 */
const doQuitTeam = async (id: number) => {
  const res = await myAxios.post('/team/quit', {
    teamId: id
  });
  // @ts-ignore
  if(res?.code === 0) {
    showSuccessToast('退出队伍成功');
    // location.reload();
    // 本地响应更新
    const teamIndex = props.teamList.findIndex(team => team.id === id);
    if (teamIndex!== - 1) {
      props.teamList[teamIndex].hasJoin = false;
      // @ts-ignore
      props.teamList[teamIndex].hasJoinNum = props.teamList[teamIndex].hasJoinNum - 1;
    }
  } else {
    // @ts-ignore
    showFailToast('退出队伍失败' + (res.description ? `${res.description}` : ''));
  }
}

/**
 * 解散队伍
 * @param id
 */
const doDisbandTeam = async (id: number) => {
  const res = await myAxios.post('/team/disband', {
    teamId: id
  });
  // @ts-ignore
  if(res?.code === 0) {
    showSuccessToast('解散队伍成功');
    location.reload();
  } else {
    // @ts-ignore
    showFailToast('解散队伍失败' + (res.description ? `${res.description}` : ''));
  }
}

</script>

<style scoped>
#teamCardList :deep(.van-image__img) {
  height: 128px;
  object-fit: unset;
}
#publicTag {
  margin-top: 7px;
  margin-bottom: 7px;
  --van-tag-font-size: 13px;
}
#secretTag {
  margin-top: 7px;
  margin-bottom: 7px;
  --van-tag-font-size: 13px;
  opacity: 90%;
}
#privateTag {
  margin-top: 7px;
  margin-bottom: 7px;
  --van-tag-font-size: 13px;
  opacity: 85%;
}
#keywordsDisbandTeamFontSize {
  font-size: 20px;
}
#disbandTeamButton {
  opacity: 78%;
}
</style>